<?php

namespace Biz\service\NewProduct;

use Biz\model\brandActivity\BrandActivityBasic;
use Biz\model\NewProduct\NewProductJoinRecordModel;
use Biz\model\NewProduct\NewProductTagModel;
use Biz\model\NewProduct\NewProductWikiModel;
use Biz\model\wiki\WikiBasic;
use Biz\service\brand\BrandActivity;
use Doraemon\tools\ImgUrl;
use Hhz\Medoo\Medoo;

/**
 * Description: 新品速递 service
 * Created by PhpStorm.
 * User: 玉坤
 * Date: 2021/5/20
 * Time: 11:45
 */
class NewProductService
{
    public const SUPER_PDT_SHOW_DAY = '+30 days';
    public const GRACE_PDT_SHOW_DAY = '+15 days';

    /**
     * 获取活动中wiki列表
     * @param $where
     * @param $field
     * @param $start
     * @param $offset
     * @return array|bool
     */
    public static function getNewProductInfo($where, $field, $start, $offset)
    {
        $where['status'] = NewProductWikiModel::STATUS_PASS;
        $where['is_delete'] = NewProductWikiModel::NO_DELETED;
        $where["LIMIT"] = [$start, $offset];
        $now_time = date("Y-m-d H:i:s");
        $where['start_time[<=]'] = $now_time;
        $where['end_time[>]'] = $now_time;
        $list = NewProductWikiModel::all($where, $field);
        if (!$list) {
            return [];
        }
        return $list;
    }


    /**
     * 获取往期活动列表
     * @param $field
     * @param $start
     * @param $offset
     * @param $day
     * @return array|bool
     */
    public static function getBeforeList($field, $start, $offset, $day)
    {
        $month = date('Y-m', strtotime($day));
        $end_date = date('Y-m-d');
        $where['end_time[<=]'] = $end_date;
        $where['month'] = $month;
        $where['status'] = NewProductWikiModel::STATUS_PASS;
        $where['open_status'] = NewProductWikiModel::OPEN_STATUS_CREATED;
        $where['is_delete'] = NewProductWikiModel::NO_DELETED;
        $where["LIMIT"] = [$start, $offset];
        $where['ORDER'] = [
            'end_time' => 'DESC'
        ];
        $list = NewProductWikiModel::all($where, $field);
        if (!$list) {
            return [];
        }
        return $list;
    }

    /**
     * 获取某期数量
     * @param $day
     * @return bool|int|mixed|string
     */
    public static function getBeforeListCount($day)
    {
        $month = date('Y-m', strtotime($day));
        $end_date = date('Y-m-d');
        $where['end_time[<=]'] = $end_date;
        $where['month'] = $month;
        $where['status'] = NewProductWikiModel::STATUS_PASS;
        $where['open_status'] = NewProductWikiModel::OPEN_STATUS_CREATED;
        $where['is_delete'] = NewProductWikiModel::NO_DELETED;
        return NewProductWikiModel::count($where);

    }

    /**
     * 根据活动id获取对应标签
     * @param array $ids
     * @return array|bool
     */
    public static function getTagsByNid($ids)
    {
        $tag_where['status'] = NewProductTagModel::STATUS_ON;
        $tag_where['nid'] = $ids;
        return NewProductTagModel::all($tag_where, ['tag', 'nid', 'id']);
    }

    /**
     * 获取选择不同标签的人数
     * @param $nid
     * @return array|bool
     */
    public static function getJoinRecordData($nid)
    {
        $where['new_product_join_record.nid'] = $nid;
        $where['new_product_tag.status'] = NewProductTagModel::STATUS_ON;
        $where['GROUP'] = 'new_product_tag.id';
        $field = [
            'person_num' => Medoo::raw("count('new_product_join_record.id')"),
            'tag',
            'tid'
        ];
        return NewProductTagModel::left_join('new_product_join_record', 'id', 'tid', $field, $where);
    }

    /**
     * 获取参加活动的总人数
     * @param $nid
     * @return array|bool
     */
    public static function getJoinUserCount($nid)
    {
        $where['nid'] = $nid;
        $where['GROUP'] = 'uid';
        $field = [
            'nid',
            'p_num' => Medoo::raw("count('id')"),
        ];
        return NewProductJoinRecordModel::all($where, $field);
    }

    /**
     * 获取选择不同标签的人数
     * @param $nid
     * @return array|bool
     */
    public static function getJoinRecord($nid)
    {
        $where['nid'] = $nid;
        $where['ORDER'] = ['create_time' => "DESC"];
        $where['LIMIT'] = 20;
        $records = NewProductJoinRecordModel::all($where, ['nid', 'uid', 'tid']);
        if (!$records) {
            return [];
        }
        $tagWhere['nid'] = $nid;
        $tagList = NewProductTagModel::all($tagWhere, "*");
        $tagList = array_column($tagList, 'tag', 'id');
        foreach ($records as &$record) {
            $record['tag'] = $tagList[$record['tid']] ?? '';
        }
        shuffle($records);
        return $records;
    }

    /**
     * 获取用户喜欢状态
     * @param $nids
     * @param $uid
     * @param int $type
     * @return array|bool
     */
    public static function getUserIsLike($nids, $uid, int $type = NewProductWikiModel::SUPER_PDT)
    {
        $where['GROUP'] = 'nid';
        $where['nid'] = $nids;
        $where['uid'] = $uid;
        $where['type'] = $type;
        return NewProductJoinRecordModel::all($where, '*');
    }

    /**
     * 获取用户参加活动的 标签id
     * @param $uid
     * @param $nid
     * @param int $type
     * @return array|bool
     */
    public static function getRecordForUser($uid, $nid, $type = NewProductWikiModel::SUPER_PDT)
    {
        $where['uid'] = $uid;
        $where['type'] = $type;
        $where['nid'] = $nid;
        return NewProductJoinRecordModel::value($where, 'tid');
    }

    /**
     * 新品速递活动是否在传入分类中
     * @param $cate_id
     * @return bool
     */
    public static function getIssetByCateId($cate_id): bool
    {
        $where['status'] = NewProductWikiModel::STATUS_PASS;
        $where['is_delete'] = NewProductWikiModel::NO_DELETED;
        $now_time = date("Y-m-d H:i:s");
        $where['start_time[<=]'] = $now_time;
        $where['end_time[>]'] = $now_time;
        $basic_ids = NewProductWikiModel::all($where, 'basic_id');
        $basic_ids = array_unique($basic_ids);
        $cate_info = WikiBasic::getInfosByIds($basic_ids,
            ['category_id', 'second_category_id', 'third_category_id', 'four_category_id']);
        $cate_ids = [];
        foreach ($cate_info as $info) {
            $cate_ids = array_merge($cate_ids, array_values($info));
        }
        $cate_ids = array_filter($cate_ids);
        if (in_array($cate_id, $cate_ids, false)) {
            return true;
        }
        return false;
    }

    /**
     * 获取单条活动信息
     * @param $id
     * @param string $field
     * @return array|bool
     */
    public static function getNewProductWikiInfo($id, $field = 'id')
    {
        $where['id'] = $id;
        return NewProductWikiModel::value($where, $field);
    }

    /**
     * 获取活动列表
     * @param $where
     * @return array|bool
     */
    public static function getNewActList($where)
    {
        $where['is_delete'] = NewProductWikiModel::NO_DELETED;
        return NewProductWikiModel::all($where, '*');
    }


    /**
     * 通过品牌id获取品牌活动数量
     * @param $brand_id
     * @return array|bool
     */
    public static function getNewActNumByBrandId($brand_id)
    {
        $where['is_delete'] = NewProductWikiModel::NO_DELETED;
        $where['status[!]'] = NewProductWikiModel::STATUS_REJECT;
        $where['brand_id'] = $brand_id;
        return NewProductWikiModel::count($where);
    }

    /**
     * 审核操作
     * @param $params
     * @return bool
     */
    public static function audit($params): bool
    {
        $where['id'] = $params['id'];
        $data['status'] = $params['status'];
        $data['update_time'] = date('Y-m-d H:i:s');
        $data['admin_id'] = $params['admin_id'];
        NewProductWikiModel::update($data, $where);
        return true;
    }


    /**
     * 增加活动虚拟状态
     * @param $list
     * @return array
     */
    public static function formatList($list): array
    {
        $now = time();
        $ids = array_column($list, 'id');
        $countMap = NewProductWinnerListService::getCountByNid($ids);
        $jdCardMap = NewProductWinnerListService::getCountJdCardByNid($ids);
        foreach ($list as &$info) {
            $start_time = strtotime($info['start_time']);
            $end_time = strtotime($info['end_time']);
            if ((int)$info['status'] === NewProductWikiModel::STATUS_PASS) {
                if ($start_time <= $now && $end_time > $now) {
                    $info['status'] = 3; //活动中
                }

                if ($end_time < $now) {
                    $info['status'] = 4; //活动结束
                }
            }
            $act_status_arr = NewProductWikiModel::ACT_STATUS;
            $info['status_name'] = $act_status_arr[$info['status']];
            $info['price'] /= 100;
            $info['img_url'] = ImgUrl::getUrl(ImgUrl::APPTYPE_BIZ, $info['img'], ImgUrl::IMAGE_SIZE_ORI_NPHONE) ?? '';
            $info['not_send_prize_num'] = $countMap[$info['id']] ?? 0; //未发放奖品数量
            $info['jd_card_count'] = $jdCardMap[$info['id']] ?? 0; //京东卡数量
            $info['dynamic_img'] = BrandActivity::getActivityDynamicImg(BrandActivityBasic::ACTIVITY_TYPE_NEW_PRODUCT,
                    $info['dynamic_img']) ?? '';
        }
        return $list;
    }

    /**
     * 获取活动form数据
     * @param $params
     * @return array
     */
    public static function _getData($params): array
    {
        $data['brand_id'] = $params['brand_id'] ?? 0;
        $data['brand_name'] = $params['brand_name'] ?? '';
        $data['prize_name'] = $params['prize_name'] ?? '';
        $data['basic_id'] = $params['basic_id'] ?? 0;
//        $data['wiki_id'] = $params['wiki_id'] ?? 0;
        $data['price'] = $params['price'] ? $params['price'] * 100 : 0;
        $data['url'] = $params['url'] ?? '';
        $data['type'] = $params['type'] ?? 0;
        $data['img'] = $params['img'] ?? '';
        $data['name'] = $params['name'] ?? '';
        $data['desc'] = $params['desc'] ?? '';
        $data['features'] = $params['features'] ?? '';
        $data['question'] = $params['question'] ?? '';
        $data['start_time'] = date('Y-m-d 00:00:00', strtotime($params['start_time'])) ?? '0000-00-00 00:00:00';
        $data['month'] = date('Y-m', strtotime($params['start_time'])) ?? '';
        $data['prize_num'] = $params['prize_num'] ?? 0;
        $data['jump_type'] = $params['jump_type'] ?? 1;
        $data['status'] = $params['status'] ? NewProductWikiModel::STATUS_WAIT : NewProductWikiModel::STATUS_DRAFT;
        if ((int)$params['type'] === NewProductWikiModel::SUPER_PDT) {
            //超级新品 31
            $data['end_time'] = date('Y-m-d 00:00:00',
                strtotime(self::SUPER_PDT_SHOW_DAY, strtotime($data['start_time'])));
            $data['end_time'] = date('Y-m-d H:i:s', strtotime($data['end_time']) + 86399);
            $data['dynamic_status'] = NewProductWikiModel::UNCREATED;
        } else {
            //甄选新品 21
            $data['end_time'] = date('Y-m-d 00:00:00',
                strtotime(self::GRACE_PDT_SHOW_DAY, strtotime($data['start_time'])));
            $data['end_time'] = date('Y-m-d H:i:s', strtotime($data['end_time']) + 86399);
            $data['dynamic_status'] = NewProductWikiModel::CREATED;
            $data['dynamic_img'] = NewProductWikiModel::IMG_ID_GRACE_PDT;
        }
        return $data;
    }

    /**
     * 通过id集合获取活动信息
     * @param $ids
     * @param string $field
     * @return array|bool
     */
    public static function getNewProByIds($ids, $field = '*')
    {
        $where['status'] = NewProductWikiModel::STATUS_PASS;
        $where['is_delete'] = NewProductWikiModel::NO_DELETED;
        $where['id'] = $ids;
        return NewProductWikiModel::all($where, $field);
    }


    public static function getUserLikeList($uid, $field = '*')
    {
        $where['GROUP'] = 'nid';
        $where['uid'] = $uid;
        return NewProductJoinRecordModel::all($where, $field);
    }

    /**
     * @return array|bool
     */
    public static function getForPushSystemNotificationList()
    {
        $where['end_time[<]'] = date('Y-m-d H:i:s', time());
        $where['is_delete[!]'] = NewProductWikiModel::DELETED;
        $where['status'] = NewProductWikiModel::STATUS_PASS;
        $where['type'] = NewProductWikiModel::SUPER_PDT;
        $where['system_msg_push_status[<]'] = NewProductWikiModel::SYSTEM_MSG_PUSH_STATUS_TWO;
        return NewProductWikiModel::select(['id', 'brand_id', 'prize_num', 'system_msg_push_status'], $where);
    }


    /**
     * 参与活动记录
     * @param $where
     * @return array|bool
     */
    public static function getRecordList($where)
    {
        $field = ['nid', 'uid', 'type', 'fans', 'tid', 'brand_id', 'create_time'];
        $record_list = NewProductJoinRecordModel::all($where, $field);
        if (!$record_list) {
            return [];
        }
        $tids = array_column($record_list, 'tid');
        $tag_where['id'] = $tids;
        $tag_list = NewProductTagModel::all($tag_where, ['id', 'tag']);
        if (!$tag_list) {
            return [];
        }
        $tag_list = array_column($tag_list, 'tag', 'id');
        $nids = array_column($record_list, 'nid');
        $field = ['brand_name', 'name', 'id'];
        $act_list = NewProductWikiModel::all(['id' => $nids], $field);
        if (!$act_list) {
            return [];
        }
        $act_list = array_column($act_list, null, 'id');
        foreach ($record_list as &$list) {
            //tag
            if (isset($tag_list[$list['tid']])) {
                $list['tag'] = $tag_list[$list['tid']];
            }
            //act
            if (isset($act_list[$list['nid']]['name'])) {
                $list['name'] = $act_list[$list['nid']]['name'];
            }
            if (isset($act_list[$list['nid']]['brand_name'])) {
                $list['brand_name'] = $act_list[$list['nid']]['brand_name'];
            }
        }
        return $record_list;
    }


}
